<template>
  <div>
    <a-card class="card" title="数据图表">
      <a-select v-model="chartSelect" style="width: 180px" @change="getChartData">
        <a-select-option value="impression">展现</a-select-option>
        <a-select-option value="click">点击</a-select-option>
        <a-select-option value="cost">消费</a-select-option>
        <a-select-option value="ctr">点击率</a-select-option>
        <a-select-option value="ctProductPaySuccess">商品支付成功量</a-select-option>
        <a-select-option value="ctLiveOrderConversions">直播间成单量</a-select-option>
      </a-select>
      <div id="chart-main" style="height:500px"></div>
    </a-card>
    <a-card class="card" title="数据饼图">
      <shujuBingtu :list="dataSourceTotal" />
    </a-card>
    <a-card class="card" title="数据列表">
      <a-input-search style="width:300px;margin-bottom:20px;" placeholder="输入账户名" enter-button="搜索" @search="onSearch"  allowClear/>
      <div>
        <!-- <a-space class="operator">
          <a-button @click="addNew" type="primary">新建</a-button>
        </a-space> -->
        <standard-table
          rowKey="id"
          :loading='loading'
          :columns="columns"
          :dataSource="dataSource"
          :expandedRowKeys='expandedRowKeys'
          :pagination="{showTotal:total => `共 ${total} 条数据`,showSizeChanger:true,pageSizeOptions:['10', '20', '30', '40', '50', '100']}"
          @clear="onClear"
          @change="onChange"
          @onExpand="onExpand"
          :scroll="{ x: 800 }"
        >
          <div slot="impression" slot-scope="{record}">
            {{record.impression}} 
            <span :class="record.huanbi.impression>0?'fontGreen':'fontRed'">{{record.huanbi.impression + '%'}}</span>
          </div>
          <div slot="click" slot-scope="{record}">
            {{record.click}} 
            <span :class="record.huanbi.click>0?'fontGreen':'fontRed'">{{record.huanbi.click + '%'}}</span>
          </div>
          <div slot="ctr" slot-scope="{record}">
            {{(record.ctr*100).toFixed(2) + '%'}}
            <span :class="record.huanbi.ctr>0?'fontGreen':'fontRed'">{{record.huanbi.ctr + '%'}}</span>
          </div>
          <div slot="pct" slot-scope="{record}">
            {{(record.pct).toFixed(2)}}
            <span :class="record.huanbi.pct>0?'fontGreen':'fontRed'">{{record.huanbi.pct + '%'}}</span>
          </div>
          <div slot="act" slot-scope="{record}">
            {{(record.act).toFixed(2)}}
            <span :class="record.huanbi.act>0?'fontGreen':'fontRed'">{{record.huanbi.act + '%'}}</span>
          </div>
          <div slot="cost" slot-scope="{record}">
            {{(record.cost).toFixed(2)}}
            <span :class="record.huanbi.cost>0?'fontGreen':'fontRed'">{{record.huanbi.cost + '%'}}</span>
          </div>
          <div slot="ctProductPaySuccess" slot-scope="{record}">
            {{record.ctProductPaySuccess}} 
            <span :class="record.huanbi.ctProductPaySuccess>0?'fontGreen':'fontRed'">{{record.huanbi.ctProductPaySuccess + '%'}}</span>
          </div>
          <div slot="ctLiveOrderConversions" slot-scope="{record}">
            {{record.ctLiveOrderConversions}} 
            <span :class="record.huanbi.ctLiveOrderConversions>0?'fontGreen':'fontRed'">{{record.huanbi.ctLiveOrderConversions + '%'}}</span>
          </div>
        </standard-table>
      </div>
    </a-card>
  </div>
</template>

<script>
import {delBdAccount} from '@/api/xinxiliu/account'
import StandardTable from '@/components/table/StandardTable'
import {getCampaignReportByDate} from '@/api/shuju/shuju'
import shujuBingtu from './components/shujuBingtu'
import * as echarts from 'echarts';

const columns = [
  {
    title: '推广计划',
    width: 600,
    dataIndex: 'campaignNameStatus',
  },
  {
    title: '账户',
    width: 200,
    dataIndex: 'userName'
  },
  {
    title: '展现',
    width: 200,
    dataIndex: 'impression',
    scopedSlots: { customRender: 'impression' },
    sortDirections:['descend','ascend'],
    sorter: () => {},
  },
  {
    title: '点击',
    width: 200,
    dataIndex: 'click',
    scopedSlots: { customRender: 'click' },
    sortDirections:['descend','ascend'],
    sorter: () => {},
  },
  {
    title: '消费',
    width: 200,
    dataIndex: 'cost',
    defaultSortOrder: 'descend',
    scopedSlots: { customRender: 'cost' },
    sortDirections:['descend','ascend'],
    sorter: () => {},
  },
  {
    title: '点击率',
    width: 200,
    dataIndex: 'ctr',
    scopedSlots: { customRender: 'ctr' },
    sortDirections:['descend','ascend'],
    sorter: () => {},
  },
  {
    title: '客单价',
    width: 200,
    dataIndex: 'pct',
    scopedSlots: { customRender: 'pct' },
    sortDirections:['descend','ascend'],
    sorter: () => {},
  },
  {
    title: '平均每单成本',
    width: 200,
    dataIndex: 'act',
    scopedSlots: { customRender: 'act' },
    sortDirections:['descend','ascend'],
    sorter: () => {},
  },
  {
    title: '商品支付成功量',
    width: 200,
    dataIndex: 'ctProductPaySuccess',
    scopedSlots: { customRender: 'ctProductPaySuccess' },
    sortDirections:['descend','ascend'],
    sorter: () => {},
  },
  {
    title: '直播间成单量',
    width: 200,
    dataIndex: 'ctLiveOrderConversions',
    scopedSlots: { customRender: 'ctLiveOrderConversions' },
    sortDirections:['descend','ascend'],
    sorter: () => {},
  },
]

export default {
  name: 'account',
  components: {StandardTable,shujuBingtu},
  data () {
    return {
      mod:'normal',

      advanced: true,
      columns: columns,
      selectedRows: [],
      loading:false,

      count:0,
      limit:10,
      page:1,
      dataSource: [],
      dataSourceTotal: [],
      keyWord:'',

      detail_id:0,
      expandedRowKeys:[],

      changeKey:'cost',
      changeOrder:'DESC',

      chartData:[],
      chartSelect:'cost',

      myChart:'',
    }
  },
  created() {
    this.init()
  },
  mounted(){
    setTimeout(() => {
      this.myChart = echarts.init(document.getElementById('chart-main'));
      this.myChart.showLoading({
        text: 'loading',
      });
    },0)
  },
  methods: {
    init(){
      this.getUserData()
      this.getChartData()
    },
    getUserData(){
      const _this = this;
      this.loading = true;
      let params = {
        column:this.changeKey,
        sortrule:this.changeOrder
      }
      getCampaignReportByDate(params).then((res) => {
        _this.loading = false;
        if(res.errcode == 0){
          let idx = 1
          for(let item of res.data){
            item.id = idx
            let huanbi = {
              act: this.getHuanbi(item,'act'),
              click: this.getHuanbi(item,'click'),
              cost: this.getHuanbi(item,'cost'),
              cpc: this.getHuanbi(item,'cpc'),
              ctLiveOrderConversions: this.getHuanbi(item,'ctLiveOrderConversions'),
              ctProductPaySuccess: this.getHuanbi(item,'ctProductPaySuccess'),
              ctProductPaySuccessAmount: this.getHuanbi(item,'ctProductPaySuccessAmount'),
              ctProductPaySuccessAmountROI: this.getHuanbi(item,'ctProductPaySuccessAmountROI'),
              ctr: this.getHuanbi(item,'ctr'),
              impression: this.getHuanbi(item,'impression'),
              pct: this.getHuanbi(item,'pct'),
            }
            item.huanbi = huanbi
            idx++
          }
          console.log(res.data) 
          _this.dataSource = res.data
          _this.dataSourceTotal = res.data
          if(_this.keyWord != ''){
            _this.onSearch(_this.keyWord)
          }
        }
      });
    },
    getHuanbi(item,key){
      let today = item[key]?item[key]:0
      let yesdata = item.yesdata?item.yesdata[key]?item.yesdata[key]:0:0
      let huanbi = '-'
      if(yesdata != 0 && today != 0){
        huanbi = (today - yesdata)/yesdata*100
        huanbi = huanbi.toFixed(2)
      }else if(yesdata == 0 && today == 0){
        huanbi = 0
      }
      return huanbi
    },
    getChartData(){
      const _this = this;
      let params = {
        column:this.chartSelect,
        sortrule:'DESC'
      }
      getCampaignReportByDate(params).then((res) => {
        if(res.errcode == 0){
          _this.chartData = res.data
          _this.createChart()
        }
      });
    },
    createChart(){
      let first10List = this.chartData.slice(0,10)
      let xAxisArr = []
      let seriesArr = []
      for(let item of first10List){
        xAxisArr.push(item.campaignNameStatus)
        seriesArr.push(item[this.chartSelect])
      }
      // console.log('first10List',first10List,xAxisArr,seriesArr)
      let options = {}
      if(window.innerWidth > 750){
        options = {
          xAxis: {
            type: 'category',
            data: xAxisArr,
            axisTick: {
              alignWithLabel: true
            },
            axisLabel: {  
              interval: 0,  
              formatter: function (value) {
                var ret = "";
                var maxLength = 10;
                var valLength = value.length;
                var rowN = Math.ceil(valLength / maxLength);
                if (rowN > 1) {
                  for (var i = 0; i < rowN; i++) {
                    temp = "";
                    var start = i * maxLength;
                    var end = start + maxLength;
                    var temp = value.substring(start, end) + "\n";
                    ret += temp;
                  }
                  return ret;
                } else {
                  return value;
                }
              },
            },
            // axisLabel: { interval: 0, rotate: -20 }
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              data: seriesArr,
              type: 'bar'
            }
          ]
        }
      }else{
        options = {
          yAxis: {
            type: 'category',
            data: xAxisArr,
            axisTick: {
              alignWithLabel: true
            },
            axisLabel: {  
              interval: 0,  
              formatter: function (value) {
                var ret = "";
                var maxLength = 10;
                var valLength = value.length;
                var rowN = Math.ceil(valLength / maxLength);
                if (rowN > 1) {
                  for (var i = 0; i < rowN; i++) {
                    temp = "";
                    var start = i * maxLength;
                    var end = start + maxLength;
                    var temp = value.substring(start, end) + "\n";
                    ret += temp;
                  }
                  return ret;
                } else {
                  return value;
                }
              },
            },
            // axisLabel: { interval: 0, rotate: -20 }
          },
          xAxis: {
            type: 'value'
          },
          series: [
            {
              data: seriesArr,
              type: 'bar'
            }
          ]
        }
      }
      
      this.myChart.hideLoading()
      this.myChart.setOption(options)
    },
    onSearch(userName){
      this.keyWord = userName
      if(userName != ''){
        this.dataSource = this.dataSourceTotal.filter(o=>o.userName == userName)
      }else{
        this.dataSource = this.dataSourceTotal
      }
    },
    edit(id){
      this.detail_id = id
      this.mod = 'edit'
    },
    deleteRecord(id) {
      delBdAccount({id}).then(() => {
        this.$message.success('删除成功')
        this.init()
      });
    },
    onExpand(bool, row){
      if(bool){
        this.expandedRowKeys.push(row.id)
      }else{
        let idx = this.expandedRowKeys.findIndex(e=>e == row.id)
        this.expandedRowKeys.splice(idx,1)
      }
      console.log("onExpand", bool, row,this.expandedRowKeys)
    },
    getSorter(sorter){
      if(sorter.column){
        this.changeKey = sorter.column.dataIndex
        switch(sorter.order){
          case "ascend":
            this.changeOrder = 'ASC'
            break
          case "descend":
            this.changeOrder = 'DESC'
            break
        }
        this.init()
      }else{
        this.changeKey = ''
        this.changeOrder = ''
      }
    },

    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    remove () {
      this.dataSource = this.dataSource.filter(item => this.selectedRows.findIndex(row => row.key === item.key) === -1)
      this.selectedRows = []
    },
    onClear() {
      this.$message.info('您清空了勾选的所有行')
    },
    onStatusTitleClick() {
      this.$message.info('你点击了状态栏表头')
    },
    onChange(pagination, filters, sorter,) {
      console.log(pagination, filters, sorter)
      if(this.page == pagination.current){
        this.getSorter(sorter)
      }
      this.page = pagination.current
      // this.init()
    },
    onSelectChange() {
      this.$message.info('选中行改变了')
    },
    handleMenuClick (e) {
      if (e.key === 'delete') {
        this.remove()
      }
    },
    goXinxiliu(id,name){
      this.$store.commit('dianpu/setId',{id,name})  //保存id
      this.$router.push('/xinxiliu')
    }
  },
  watch:{
    mod(e){
      if(e=='normal'){
        this.init()
      }
    }
  },
  filters:{
    getStatus(e){
      switch(e){
        case 1:case '1':
          return '正常'
        case 2:case '2':
          return '异常'
      }
    }
  }
}
</script>

<style lang="less" scoped>
  .fontGreen{
    margin-left: 10px;
    color: #41b883;
  }
  .fontRed{
    margin-left: 10px;
    color: #c96168;
  }
  .card{
    margin-bottom: 20px;
  }
  .search{
    margin-bottom: 54px;
  }
  .fold{
    width: calc(100% - 216px);
    display: inline-block
  }
  .operator{
    margin-bottom: 18px;
  }
  @media screen and (max-width: 900px) {
    .fold {
      width: 100%;
    }
  }
</style>
